<template>
    <div class="e-form">
        <BillTop @cancel="printHandel"></BillTop>
        <div class="tabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="结算清单" name="qingdan" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="工程材料理论量" name="lilunliang" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="材料理论/实际消耗" name="xiaohao" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%;" class="form">
                            <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="240px">
                              <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="结算编号：">
                                                {{ formData.billNo }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="期数：">
                                                {{ formData.period }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="合同名称："
                                                prop="contract"
                                            >
                                            {{formData.contractName}}
                                            &nbsp;
                                                <span
                                                    class="goTo"
                                                    @click="
                                                        goToContract(
                                                            formData.contractId
                                                        )
                                                    "
                                                    v-if="formData.contractId"
                                                    >查看合同</span
                                                >
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="外包方：">
                                                {{ formData.outsourcerName }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                        <el-form-item label="结算日期：">
                                                {{formData.settlementDate}}
                                        </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="冲产业工人工资："
                                                prop="writeOffWages"
                                            >
                                            {{formData.writeOffWages}}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="本期结算金额(不含保证金)："
                                            >
                                             {{ currentAmountNoBond }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="保证金合计：">
                                                {{ bondTotal }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="税率%：">
                                                {{ formData.taxRate }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="本期结算金额(含保证金)："
                                            >
                                               {{
                                                    currentAmountNoBond + bondTotal
                                                }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="税额(元)："
                                            >
                                            {{formData.taxAmount}}
                                            </el-form-item>
                                        </el-col>

                                        <el-col :span="12">
                                            <el-form-item
                                                label="本期结算金额(含税)："
                                            >
                                           {{ currentAmountHaveTax }}
                                            <el-tooltip
                                            content="本期结算金额（含税）=本期结算金额（不含保证金）+税额"
                                            placement="top"
                                            >
                                            <i
                                            class="
                                                el-icon-warning-outline
                                                greenFont
                                            "
                                            ></i>
                                                </el-tooltip>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="状态：">
                                                {{ stateLable(formData.state) }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="传财务共享：">
                                                 <span :class="isFontColor ? 'redFont' : 'greenFont'">{{shareLable(formData.easId)}}</span>
                                                <el-tooltip
                                                    content="预计xxx时间传输财务"
                                                    placement="top"
                                                >
                                                    <i
                                                        class="
                                                            el-icon-warning-outline
                                                            greenFont
                                                        "
                                                    ></i>
                                                </el-tooltip>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="币种：">
                                                {{ formData.currency }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="本位币：">
                                                {{ formData.baseCurName }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="本位币汇率："
                                            prop="baseCurRate">
                                            {{formData.baseCurRate}}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="人民币汇率：">
                                                {{ formData.rmbRate }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="录入机构：">
                                                {{ formData.orgName }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="录入日期：">
                                                {{ formData.gmtCreate }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="24">
                                            <el-form-item
                                                label="本期结算内容概要："
                                            >
                                                <el-input
                                                    placeholder=""
                                                    v-model="formData.remarks"
                                                    class="input-with-select"
                                                    type="textarea"
                                                    :rows="3"
                                                >
                                                    <span>
                                                        {{ formData.remarks }}
                                                    </span>
                                                </el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                    <el-row v-if='formData.state==5'>
                    <el-col :span="12">
                        <el-form-item label="作废原因：">
                           {{formData.nullifyReason}}
                        </el-form-item>
                    </el-col>
                     <el-col :span="12">
                        <el-form-item label="作废说明：">
                           {{formData.nullifyDescription}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if='formData.state==5'>
                    <el-col :span="12">
                        <el-form-item label="作废人：">
                           {{formData.nullifyCreator}}
                        </el-form-item>
                    </el-col>
                     <el-col :span="12">
                        <el-form-item label="作废时间：">
                           {{formData.nullifyCreated}}
                        </el-form-item>
                    </el-col>
                </el-row>
                            </el-form>
                        </div>
                    </div>
                    <div id="qingdanCon" class="con">
            <div>
            <div class="e-table e-tree-table " style="background-color: #fff">
                    <!-- 结算清单 -->
                        <div id="changeDetailCon" class="con">
                            <div class="tabs-title" id="qingdan">
                                结算清单
                            </div>
                        </div>
                         <div class="errMessageBox">
                                <p class="errMessage" v-for="(item,index) in settlementErrorList" :key='index'>
                                    {{item}}
                                </p>
                        </div>
                  <div class="bigBox">
                            <div class="top">
                                <div class="left">
                                    <div class="select_box">
                                        <el-button
                                            size="small"
                                            class="btn-greenYellow"
                                            @click="
                                                settleOrgChange(
                                                    formData.contractId
                                                )
                                            "
                                        >
                                            引入清单</el-button
                                        >
                                        <span class="label"
                                            >查看清单范围：</span
                                        >
                                        <el-radio-group v-model="qingdanRange" @change="selectionList">
                                            <el-radio label="1"
                                                >本期结算清单</el-radio
                                            >
                                            <el-radio label="all"
                                                >全部清单</el-radio
                                            >
                                        </el-radio-group>
                                        <span class="label" v-if="formData.contractTypeValue == '1'"
                                            >查看清单维度：</span
                                        >
                                        <el-radio-group v-model="structure" v-if="formData.contractTypeValue == '1'">
                                            <el-radio label="1"
                                                >细目—>结构部位</el-radio
                                            >
                                            <el-radio label="2"
                                                >结构部位—>细目</el-radio
                                            >
                                        </el-radio-group>
                                        <span class="label">期数：</span>
                                        <div style="flex: 1">
                                            <el-select
                                                multiple
                                                v-model="qishu"
                                                collapse-tags
                                                placeholder="请选择"
                                                @change="onSelectQishu"
                                            >
                                                <el-option
                                                    v-for="item in qishuOptions"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                ></el-option>
                                            </el-select>
                                        </div>
                                    </div>
                                </div>
                                <div class="right">
                                    <div>
                                        <el-input
                                            placeholder="请输入细目编号、细目名称或结构部位进行搜索"
                                            size="small"
                                            v-model="searchVal"
                                        >
                                            <img
                                                src="@/assets/search.png"
                                                slot="suffix"
                                                @click="searchTableData"
                                            />
                                        </el-input>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- 表格 -->
                        <div class="e-table e-tree-table">
                            <!-- default-expand-all 默认展开全部 -->
                            <el-table
                                :data="acceptanceData"
                                border
                                ref="acceptanceDataTable"
                                style="width: 100%"
                                @cell-mouse-enter="cellMouseEnter"
                                @cell-mouse-leave="cellMouseLeave"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                lazy
                                :load="onload"
                                row-key="uuid"
                                class="table"
                                default-expand-all
                               :max-height="$store.state.tableHeight"
                                v-sortTable="{'tableData': acceptanceData, '_this': this, 'ref': 'acceptanceDataTable'}"
                            >
                                <el-table-column  fixed label="操作" width="150">
                                    <template slot-scope="{ row }">
                                        <span>{{row.serialNumber}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="itemNo"
                                    label="细目编号"
                                    fixed
                                    min-width="150"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="itemName"
                                    label="细目名称"
                                    fixed
                                    min-width="150"
                                >
                                <template slot-scope="{row}">
                                    <span
                                        @click="examine(row)"
                                        style="color: blue; cursor: pointer"
                                        v-if="row.isBillLevel == 1"
                                    >
                                        {{ row.itemName }}
                                    </span>
                                    <span v-else>
                                        {{row.itemName}}
                                    </span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    prop="structureName"
                                    label="结构部位"
                                    min-width="150"
                                >
                                <template slot-scope="{row}">
                                    <span v-if='row.type=="1"||row.type=="2"'>
                                         {{row.structureName}}
                                    </span>
                                    <span v-else>
                                       --
                                    </span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="单位"
                                    min-width="150"
                                >
                                <template slot-scope="{row}">
                                    <span v-if='row.type=="1"||row.type=="2"'>
                                         {{row.unit}}
                                    </span>
                                    <span v-else>
                                       --
                                    </span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    prop="contractQuantity"
                                    label="合同数量"
                                    min-width="150"
                                >
                                <template slot-scope="{row}">
                                    <span v-if='row.type!="3"'>
                                         {{row.contractQuantity}}
                                    </span>
                                    <span v-else>
                                       --
                                    </span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    label="合同单价"
                                    min-width="150"
                                    prop="contractPrice"
                                >
                                <template slot-scope="{row}">
                                    <span v-if='row.type=="1"||row.type=="2"'>
                                         {{row.contractPrice}}
                                    </span>
                                    <span v-else>
                                       --
                                    </span>
                                </template>
                                </el-table-column>
                                 <el-table-column
                                    label="合同金额"
                                    min-width="150"
                                    prop="contractAmount"
                                >
                                 <template slot-scope="{row}">
                                    <span v-if='row.type !="3"'>
                                         {{row.contractAmount}}
                                    </span>
                                    <span v-else>
                                       --
                                    </span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    label="本期结算数量"
                                    min-width="200"
                                    prop="settlementQuantity"
                                >
                                <template slot-scope="{ row }">
                                        <div style="display: flex; align-items: center;"  v-if="row.isDetailed=='1'&&row.type=='1'&&row.unit!='总额'">
                                        <el-input
                                            v-if="formData.state==1"
                                            v-model="row.settlementQuantity"
                                            placeholder="请输入本期结算数量"
                                            v-enterFloat2Neg="{
                                                set: row,
                                                key:'settlementQuantity'
                                            }"
                                            @change="setQuantity(row)"
                                            @focus="getOldValue(row,'settlementQuantity')"
                                        ></el-input>
                                        <span v-else>{{row.settlementQuantity}}</span>
                                            <HistoryUpDataTable :historyTableData="historyDataList"
                                            :rowData="row" isKey='settlementQuantity'/>
                                        </div>
                                        <span v-else-if="row.type==2||row.type==4">
                                          {{treeUpSummary(row,'settlementQuantity',4)}}%
                                        </span>
                                          <span v-else-if="row.type==1">
                                          {{treeUpSummary(row,'settlementQuantity',4)}}
                                        </span>
                                        <span v-else>--</span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    label="本期结算金额(元)"
                                    min-width="150"
                                    prop="settlementAmount"
                                >
                                <template slot-scope="{ row }">
                                        <div style="display: flex; align-items: center;"  v-if="row.isDetailed=='1'&&[1,2,4].includes(row.type)&&(row.type==1?row.unit == '总额':true)">
                                        <el-input
                                            v-if="formData.state==1"
                                            v-model="row.settlementAmount"
                                            placeholder="请输入本期结算金额"
                                            v-enterFloatNeg="{
                                                set: row,
                                                key: 'settlementAmount'
                                            }"
                                            @change="setAmount(row)"
                                            @focus="getOldValue(row,'settlementAmount')"
                                        ></el-input>
                                        <span v-else>{{row.settlementAmount}}</span>
                                        <HistoryUpDataTable :historyTableData="historyDataList"
                                        :rowData="row"
                                        isKey='settlementAmount'
                                        />
                                        </div>
                                        <span v-else>
                                            {{treeUpSummary(row,'settlementAmount')}}
                                        </span>
                                </template>
                                </el-table-column>
                                <!-- 第一期到第x期不包含本期数量 -->
                                <el-table-column
                                    v-for="item in dynamicLoadingLable"
                                    :label="item.label"
                                    min-width="150"
                                    :prop="item.prop"
                                    :key="item.id"
                                >
                                </el-table-column>

                                <el-table-column
                                    label="截止上期末累计结算数量"
                                    min-width="200"
                                    prop="prevTotalQuantity"
                                >
                                <template slot-scope="{ row }">
                                 <span v-if="row.type==2||row.type==4">
                                    {{treeUpSummary(row,'prevTotalQuantity',4)}}%
                                </span>
                                 <span v-else-if="row.type==1">
                                    {{treeUpSummary(row,'prevTotalQuantity',4)}}
                                </span>
                                <span v-else>--</span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    label="截止上期末累计结算金额"
                                    min-width="200"
                                    prop="prevTotalAmount"
                                >
                                <template slot-scope="{ row }">
                                     {{treeUpSummary(row,'prevTotalAmount')}}
                                </template>
                                </el-table-column>

                                <el-table-column
                                    label="截止本期末累计结算数量"
                                    min-width="200"
                                    prop="currentTotalSettlementQuantity"
                                >
                                <template slot-scope="{ row }">
                                <span v-if="row.type==2||row.type==4">
                                    {{treeUpSummary(row,'currentTotalSettlementQuantity',4)}}%
                                </span>
                                 <span v-else-if="row.type==1">
                                    {{treeUpSummary(row,'currentTotalSettlementQuantity',4)}}
                                </span>
                                <span v-else>--</span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    label="截止本期末累计结算金额"
                                    min-width="200"
                                    prop="currentTotalSettlementAmount"
                                >
                                 <template slot-scope="{ row }">
                                     {{treeUpSummary(row,'currentTotalSettlementAmount')}}
                                </template>
                                </el-table-column>
                            </el-table>
                        </div>
            </div>
        </div>
                    </div>
                    <div id="lilunliangCon" class="con">
                        <div class="tabs-title" id="lilunliang">工程材料理论量</div>
                        <lilunliang />
                    </div>
                    <div id="xiaohaoCon" class="con">
                        <div class="tabs-title" id="xiaohao">材料理论/实际消耗</div>
                        <xiaohao />
                    </div>
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="billId" bucketName="gongchengjieshuan" />
                    </div>
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <ComExaHistory :billType="billType" @getAuditHistory="getAuditHistory" :tableData="auditHistoryData" ref="ComExaHistory" />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" @exas="exas" :founderId="formData.founderId" :state="formData.state"
            :isPrint="formData.state == 1||formData.state == 2" />
            <el-button
                    type="primary"
                    class="btn-blue"
                    @click="printHandel"
                    size="small"
                    v-debounce
                    >关闭
            </el-button>
        </div>
    </div>
</template>

<script>
import { openAppClient, throttle, hideLoading, getUuid, webprintReport } from '@/utils/common'
// eslint-disable-next-line no-unused-vars
import { getBaseInfo, getDetail, delBill, modifyBaseInfo, modifyDetail, reSummary } from '@/api/settlementManagement/gongchengjieshuan/guochengjieshuan'
// eslint-disable-next-line no-unused-vars
import { getAuditHistoryLs, flowCommit, flowAudit, getCurrentState, flowUndoAudit, flownullify
} from '@/api/settlementManagement/gongchengjieshuan/jiakoukuan'
import AttachComp from '@/components/common/attachIndex'
//审核历史
import ComExaHistory from '@/components/common/exaHistory.vue'
import ComExaButtons from '@/components/common/exaButtons'
import Lilunliang from './components/lilunliang'
import Xiaohao from './components/xiaohao'
import { mapState, mapMutations } from 'vuex'
import '@/utils/jquery.scrollTo.min'
import httpRequest from '@/api/settlementManagement/gongchengjieshuan/gongchengAndzhongqi'
import HistoryUpDataTable from '@/pages/projectSettlement/components/historyUpDataTable'
export default {
    components: {
        AttachComp,
        ComExaHistory,
        ComExaButtons,
        Lilunliang,
        Xiaohao,
        HistoryUpDataTable
    },
    data () {
        return {
            tabsName: 'baseInfo',
            billType: '1099',
            billId: this.$route.query.billid,
            flowParams: {
                'billId': '',
                'billType': '',
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            //表单数据
            formData: {},
            tableDataQd: [],
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            val: '', //冲预付款金额（元）
            auditHistoryData: [],
            auditState: {},
            rules: {
                settlementType: [{ required: true, message: '请输入活动名称', trigger: ['blur', 'change'] }],
                sourceBillNo: [{ required: true, message: '外包方不能为空', trigger: ['blur', 'change'] }],
                supplierName: [{ required: true, message: '请选择结算日期', trigger: ['blur', 'change'] }],
                taxRate: [{ required: true, message: '税率不能为空', trigger: ['blur', 'change'] }],
                currency: [{ required: true, message: '币种不能为空', trigger: ['blur', 'change'] }],
                showEas: [{ required: true, message: '传输财务共享不能为空', trigger: ['blur', 'change'] }],
                baseCurName: [{ required: true, message: '本位币不能为空', trigger: ['blur', 'change'] }],
                currencyRate: [{ required: true, message: '本位币汇率不能为空', trigger: ['blur', 'change'] }],
                rmbRate: [{ required: true, message: '人民币汇率不能为空', trigger: ['blur', 'change'] }],
            },
            //获取当前页面可以操作的按钮
            buttonParams: {
                billId: this.$route.query.billid,
                billType: '1099', // 对应模块Id
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            //提交审核参数
            auditParams: {
                billId: this.$route.query.billid,
                billType: '1099',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': '1099',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false,
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            winEvent: {},
            isReviseBaseCurRate: true, //本位币汇率是否可以修改
            //结算清单明细
            acceptanceData: [],
            //工程内容
            projectContent: {
                serialNumber: 1,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '合同工程内容', //细目名称 扩大基础"
                type: 1, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '1', //每个父级的id
            },
            //预付款
            advanceCharge: {
                serialNumber: 2,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '分包预付款', //细目名称 扩大基础"
                type: 2, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '2', //每个父级的id
            },
            //加扣款
            plusDeduction: {
                serialNumber: 3,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '加扣款', //细目名称 扩大基础"
                type: 3, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '3', //每个父级的id
            },
            //税金
            taxes: {
                serialNumber: 4,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '税金', //细目名称 扩大基础"
                type: 5, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '4', //每个父级的id
            },
            //保证金
            bond: {
                serialNumber: 5,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '保证金', //细目名称 扩大基础"
                type: 4, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '5', //每个父级的id
            },
            //不含税结算价合计
            noTaxesTotalSettlement: {
                itemName: '不含税结算价合计', //细目名称 扩大基础"
                uuid: getUuid(), //表格需要的id
                itemId: '6', //每个父级的id
            },
            //含税结算价合计
            taxesTotalSettlement: {
                itemName: '含税结算价合计', //细目名称 扩大基础"
                uuid: getUuid(), //表格需要的id
                itemId: '7', //每个父级的id
            },
            //结算合计
            totalSettlement: {
                itemName: '结算合计', //细目名称 扩大基础"
                uuid: getUuid(), //表格需要的id
                itemId: '8', //每个父级的id
            },
            stageNumberTableList: [], //数量期数表格数据
            stageAmountTableList: [], //金额期数表格数据
            qingdanRange: 'all', //清单类型选择
            structure: '1',
            qishuOptions: [], //所有期数
            qishu: [], //期数vauel数组
            oldQishu: [], //保存修改之前的老数据
            errorMsg: [], //计划明细错误显示
            isFontColor: true, //传输财务共享颜色未传，返回修改 红色 财务共享审核中，已传 绿色
            historyDataList: [], //对应清单明细变更历史
            initializationData: [], //初始化数据
            searchVal: '', //表格搜索内容
            cloneTbaleData: [], //备份表格原数据
            errorList: [], //控制导航栏感叹号的显示
            settlementErrorList: [], //结算明细中用于提示错误的数据
            tabArr: [], //用于验证功能列表中的必填项
        }
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        //监听累计结算金额（不含保证金）
        currentAmountNoBond: {
            deep: true,
            handler (newVal, oldVal) {
                if(newVal == oldVal) {
                    return
                }
                this.formData.taxAmount = (newVal * this.formData.taxRate / 100).toFixed(2) * 1
                this.taxes.settlementAmount = this.formData.taxAmount || 0
                this.taxes.currentTotalSettlementAmount = ((Number(this.formData.taxAmount) || 0) +
                (Number(this.taxes.prevTotalAmount) || 0)).toFixed(2) * 1
            }
        },
        //监听合同工程内容更新不含税结算价合计
        projectContent: {
            deep: true,
            handler (newVal) {
                this.setTotalSettlement([this.plusDeduction, this.advanceCharge, newVal], this.noTaxesTotalSettlement)
                this.setTotalSettlement([this.plusDeduction, this.advanceCharge, this.taxes, newVal], this.taxesTotalSettlement)
                this.setTotalSettlement([this.plusDeduction, this.advanceCharge, this.taxes, this.bond, newVal], this.totalSettlement)
            }
        },
        //监听分包预付款更新不含税结算价合计
        advanceCharge: {
            deep: true,
            handler (newVal) {
                this.setTotalSettlement([this.plusDeduction, newVal, this.projectContent], this.noTaxesTotalSettlement)
                this.setTotalSettlement([this.plusDeduction, newVal, this.taxes, this.projectContent], this.taxesTotalSettlement)
                this.setTotalSettlement([this.plusDeduction, newVal, this.taxes, this.bond, this.projectContent], this.totalSettlement)
            }
        },
        //监听加扣款更新
        plusDeduction: {
            deep: true,
            handler (newVal) {
                this.setTotalSettlement([newVal, this.advanceCharge, this.projectContent], this.noTaxesTotalSettlement)
                this.setTotalSettlement([newVal, this.advanceCharge, this.taxes, this.projectContent], this.taxesTotalSettlement)
                this.setTotalSettlement([newVal, this.advanceCharge, this.taxes, this.bond, this.projectContent], this.totalSettlement)
            }
        },
        //监听税金更新含税结算价合计
        taxes: {
            deep: true,
            handler (newVal) {
                this.setTotalSettlement([this.projectContent, this.plusDeduction, this.advanceCharge, newVal], this.taxesTotalSettlement)
                this.setTotalSettlement([this.projectContent, this.plusDeduction, this.advanceCharge, newVal], this.totalSettlement)
            }
        },
        //监听保证金更新结算合计
        bond: {
            deep: true,
            handler (newVal) {
                this.setTotalSettlement([this.projectContent, this.plusDeduction, this.advanceCharge, this.taxes, newVal], this.totalSettlement)
            }
        }
    },
    created () {
        this.flowParams.billId = this.billId
        this.flowParams.billType = this.billType
    },
    mounted () {
        this.init()
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['baseInfo', 'qingdan', 'lilunliang', 'xiaohao', 'attach', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    computed: {
        ...mapState('equip', ['equipData']),
        ...mapState({
            userInfo: state => state.userInfo,
        }),
        //根据状态值参数决定是否展示打印按钮
        stateLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)
                return obj ? obj.label : ''
            }
        },
        //传输财务共享
        shareLable () {
            return param => {
                const state = this.$store.state.equip.equipData.shareFrom
                const obj = state.find(x => x.value == param)
                if(obj) {
                    if(obj.label == '未传' || obj.label == '返回修改') {
                        this.isFontColor = true
                    }else {
                        this.isFontColor = false
                    }
                }
                return obj ? obj.label : ''
            }
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 85 - this.lastConHeight
        },
        attachId () {
            return this.$route.query.billid
        },
        //本期结算金额不含保证金
        currentAmountNoBond () {
            let total = 0
            this.acceptanceData.forEach(item=>{
                if(item.type == 1 || item.type == 2 || item.type == 3) {
                    total += Number(item.settlementAmount)
                }
            })
            return (total || 0).toFixed(2) * 1
        },
        //保证金合计
        bondTotal () {
            let target = 0
            this.acceptanceData.forEach(item=>{
                if(item.type == 4) {
                    target = Number(item.settlementAmount)
                }
            })
            return target
        },
        //本期结算金额含税
        currentAmountHaveTax () {
            return ((Number(this.formData.taxAmount) || 0) + (Number(this.currentAmountNoBond) || 0)).toFixed(2) * 1
        },
        //根据选中期数动态展示表格
        dynamicLoadingLable () {
            const list =  []
            this.qishu.forEach(item=>{
                if(item) {
                    const obj1 = {
                        label: `第${item}期结算金额`,
                        prop: `settlementAmount${item}`,
                        id: getUuid()
                    }
                    const obj2 = {
                        label: `第${item}期结算数量`,
                        prop: `settlementQuantity${item}`,
                        id: getUuid()
                    }
                    list.push(obj1, obj2)
                }
            })
            return list
        },
    },
    methods: {
        ...mapMutations(['setSelectedInfo', 'setAuditParams']),
        //加法运算并保留任意位小数
        summationResToOrFourDecimal (a, b, decimal = 2) {
            return ((Number(a) || 0) + (Number(b) || 0)).toFixed(decimal) * 1
        },
        //树向上汇总row为当前数据,key为需要计算的属性
        treeUpSummary (row, key) {
            if(row.children && row.children.length > 0 ) {
                row[key] = row.children.reduce((count, item)=>count + (parseFloat(item[key]) || 0), 0).toFixed(2) * 1
                row[key] = row[key] || 0
            }
            return row[key]
        },
        //设置本期之前的所有期数
        setHistoryPeriods (peridos) {
            const periodsList = [{ label: '全部', value: 0 }] //第一条数据默认全部
            for (let i = 1; i <= peridos; i++) {
                const obj = {
                    label: `第${i}期`,
                    value: i
                }
                periodsList.push(obj)
            }
            const valueList = periodsList.map(item => item.value)
            this.qishuOptions = periodsList
            this.qishu = valueList
            this.oldQishu = valueList
        },
        //设置历史期数
        setTableHistoryPeriods (obj, list) {
            let max = 0 // 最大期数
            let totalAmount = 0 //累计金额
            let totalQuantity = 0 // 累计数量
            //税金参数（税金与其他的结算类型一起返回需要单独找出税金）
            let taxesMax = 0
            let taxesTotalAmount = 0
            const taxeObj = {}
            list.forEach(item=>{
                //税金type等于5没有就是目标
                if(item.type == 5) {
                    const p = item.period
                    taxeObj['settlementAmount' + p] = item.settlementAmount || 0
                    taxesTotalAmount += Number(item.settlementAmount)
                    taxesMax = Math.max(taxesMax, p)
                }else {
                    const p = item.period
                    obj['settlementAmount' + p] = item.settlementAmount || 0
                    if(obj.type == 2 || obj.type == 4) {
                        obj['settlementQuantity' + p] = item.settlementQuantity ? item.settlementQuantity + '%' : '0%'
                    }else {
                        obj['settlementQuantity' + p] = item.settlementQuantity || 0
                    }
                    totalAmount += (Number(item.settlementAmount) || 0)
                    totalQuantity += (Number(item.settlementQuantity) || 0)
                    max = Math.max(max, p)
                }
            })
            totalAmount = totalAmount.toFixed(2) * 1
            totalQuantity = totalQuantity.toFixed(4) * 1
            taxesTotalAmount = taxesTotalAmount.toFixed(2) * 1
            const arr = [
                { type: 'target', max, totalAmount, totalQuantity, other: {} },
                { type: 'taxes', max: taxesMax, totalAmount: taxesTotalAmount, totalQuantity: '', other: taxeObj
                }]
            return arr
        },
        // 审核历史列表查询
        async getAuditHistory () {
            this.auditHistoryData = await getAuditHistoryLs(this.flowParams)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                const lastCon = document.getElementById('auditHistoryCon')
                if (lastCon) {
                    const lastConHeight = lastCon.offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //前往合同页面进行查看
        goToContract (contractId) {
            openAppClient(
                `/contractDefinitionShow?billid=${contractId}&isview=true`, '查看分包合同'
            )
        },
        //切换清单事件
        selectionList (val) {
            let res = []
            if(val == 'all') {
                const list = []
                this.qishuOptions.forEach(item=>{
                    list.push(item.value)
                })
                res = list
            }
            this.qishu = res
        },
        //修改期数
        onSelectQishu (e) {
            let difference
            // 选中
            if (e.length > this.oldQishu.length) {
                difference = e.find(item => this.oldQishu.indexOf(item) === -1)
                // 选中 “全部”时
                if (difference === 0) {
                    this.qishu = this.qishuOptions.map(item => item.value)
                } else {
                    // 如果选中项数为 除了 “全部” 外的所有
                    if (e.length === this.qishuOptions.length - 1) {
                        this.qishu = this.qishuOptions.map(item => item.value)
                    }
                }
            } else {
                // 取消
                difference = this.oldQishu.find(item => e.indexOf(item) === -1)
                if (difference === 0) {
                    this.qishu = []
                } else {
                    // 如果取消之前是全部选中，则取消选中 “全部”
                    if (this.oldQishu.length === this.qishuOptions.length) {
                        this.qishu.splice(0, 1)
                    }
                }
            }
            this.oldQishu = this._.clone(this.qishu)
        },
        // elment表格事件
        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        // elment表格事件
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        //初始化数据
        init () {
            Promise.all([
                this.getInfoData (),
                this.getInfoDetailed(),
                this.getUnderReviewHistoryData()
            ]).finally(() => {
                hideLoading()
            })
        },
        //获取审核中历史修改记录
        getUnderReviewHistoryData () {
            httpRequest.getUnderReviewHistoryData({ billId: this.billId })
                .then(res=>{
                    this.historyDataList = res
                })
        },
        //获取基本信息数据
        getInfoData () {
            httpRequest.getProjectSettlementInfoData({ id: this.billId })
                .then(res=>{
                    //获取当前页面可以操作的按钮
                    httpRequest.getButtons(this.buttonParams)
                        .then(butRes => {
                            butRes.canModify = false
                            this.auditState = butRes
                        })
                    this.formData = { ...res }
                    //获取合同截止上期末累计结算金额
                    httpRequest.getPreviousTotalAmount({ contractId: res.contractId })
                        .then(data=>{
                            if(typeof data == 'number') {
                                this.formData.previousTotalAmount = data
                            }else {
                                this.formData.previousTotalAmount = 0
                            }
                        })
                })
        },
        //获取历史数据
        async getHistoryData (item) {
            const resLine = await httpRequest.getProjectSettlementHistory({
                'contractId': this.formData.contractId,
                'dtls': [
                    {
                        'marginType': item.marginType,
                        'sourceId': item.sourceId,
                        'structureId': item.structureId,
                        'type': item.type
                    }
                ],
                'orgId': this.formData.orgId,
                'period': this.formData.period || 1
            })
            return this.setTableHistoryPeriods(item, resLine)
        },
        //获取施工日志
        async getListCanSettleQuantity (item) {
            const resLine = await httpRequest.getListCanSettleQuantity({
                'contractId': this.formData.contractId,
                'dtls': [
                    {
                        'codeId': item.parentId,
                        'structureId': item.structureId,
                        'sumQty': 0
                    }
                ]
            })
            return resLine
        },
        //获取明细数据仅限父级
        getInfoDetailed () {
            httpRequest.getProjectSettlementDetailed({ billId: this.billId, parentId: '0' }).then( res=>{
                if(res.length > 0) {
                    res.forEach(item=>{
                        //获取预付款
                        if(item.isDetailed == 1) {
                            this.getHistoryData(item)
                                .then(r=>{
                                    let totalQuantity = 0
                                    let totalAmount = 0
                                    let max = 0
                                    r.forEach(o=>{
                                        //目标
                                        if(o.type == 'target') {
                                            totalQuantity = o.totalQuantity || 0
                                            totalAmount = o.totalAmount || 0
                                            max = o.max
                                            const currentTotalSettlementAmount = this.summationResToOrFourDecimal(totalAmount, item.settlementAmount)
                                            const currentTotalSettlementQuantity = this.summationResToOrFourDecimal(totalQuantity, item.settlementQuantity, 4)
                                            Object.assign(item, { prevTotalQuantity: totalQuantity, prevTotalAmount: totalAmount, currentTotalSettlementAmount, currentTotalSettlementQuantity })
                                            this.setHistoryPeriods(max)
                                        }else {
                                            const currentTotalSettlementAmount = this.summationResToOrFourDecimal(o.totalAmount, this.taxes.settlementAmount)
                                            //税金
                                            Object.assign(this.taxes, { prevTotalAmount: o.totalAmount, currentTotalSettlementAmount, ...o.other })
                                            this.setHistoryPeriods(o.max)
                                        }
                                    })
                                })
                        }
                        Object.assign(item, { children: [], hasChildren: [], uuid: getUuid() })
                    })
                    const projectContentList = res.filter(item=>item.type == 1)
                    const advanceChargeList = res.filter(item=>item.type == 2)
                    const plusDeductionList = res.filter(item=>item.type == 3)
                    const bondList = res.filter(item=>item.type == 4)
                    const plusDeductionTree =  this.listConversionTreeOther(plusDeductionList, '0', 0)
                    const advanceChargeTree = this.listConversionTreeOther(advanceChargeList, '0', 0)
                    const bondTree =  this.listConversionTreeOther(bondList, '0', 0)
                    this.projectContent.children = projectContentList
                    this.advanceCharge.children = advanceChargeTree
                    this.plusDeduction.children = plusDeductionTree
                    this.bond.children = bondTree
                    this.taxes.settlementAmount = this.formData.taxAmount
                    this.taxes.currentTotalSettlementAmount = this.formData.taxAmount
                    this.acceptanceData.push(this.projectContent, this.advanceCharge, this.plusDeduction, this.taxes, this.bond, this.noTaxesTotalSettlement, this.taxesTotalSettlement, this.totalSettlement)
                }
            })
        },
        //获取子级的数据
        async getChildrenInfo (thisLevelId) {
            const res = await httpRequest.getProjectSettlementDetailed({ billId: this.billId, parentId: thisLevelId })
            for (const key in res) {
                Object.assign(res[key], { children: [], hasChildren: true, uuid: getUuid() })
                if(res[key].isDetailed == 1) {
                    const targetList = await this.getHistoryData(res[key])
                    //当单位为总额时数量从施工日报带入
                    if(res[key].unit != '总额' && res[key].type == 1 ) {
                        const targetProjectLog = await this.getListCanSettleQuantity(res[key])
                        console.log(targetProjectLog, 'targetProjectLog')
                        // res[key].settlementQuantity = Number(targetProjectLog[0].sumQty) || 0
                        console.log(res[key].settlementQuantity, 'settlementQuantity')
                        res[key].settlementAmount = parseInt((res[key].settlementQuantity * (res[key].contractPrice || 0)))
                        res[key].currentTotalSettlementQuantity = ((Number(res[key].prevTotalQuantity) || 0) + (Number(res[key].settlementQuantity) || 0)).toFixed(4) * 1
                        res[key].currentTotalSettlementAmount = (Number(res[key].settlementAmount) || 0) + (Number(res[key].prevTotalAmount) || 0)
                        //保存当前可结算施工量
                        res[key].projectLog = Number(targetProjectLog[0].sumQty) || 0
                    }
                    let totalQuantity = 0
                    let totalAmount = 0
                    let max = 0
                    targetList.forEach(item=>{
                        //目标
                        if(item.type == 'target') {
                            totalQuantity = item.totalQuantity || 0
                            totalAmount = item.totalAmount || 0
                            max = item.max
                            const currentTotalSettlementAmount = this.summationResToOrFourDecimal(item.totalAmount, res[key].settlementAmount)
                            const currentTotalSettlementQuantity = this.summationResToOrFourDecimal(item.totalQuantity, res[key].settlementQuantity, 4)
                            Object.assign(res[key], { children: [], hasChildren: false,  prevTotalQuantity: totalQuantity, prevTotalAmount: totalAmount, currentTotalSettlementAmount, currentTotalSettlementQuantity })
                            this.setHistoryPeriods(max)
                        }else {
                            const currentTotalSettlementAmount = this.summationResToOrFourDecimal(item.totalAmount, this.taxes.settlementAmount)
                            //税金
                            Object.assign(this.taxes, { prevTotalAmount: item.totalAmount, currentTotalSettlementAmount, ...item.other })
                            this.setHistoryPeriods(item.max)
                        }
                    })

                }
            }
            return res
        },
        //懒加载数据
        async onload (row, treeNode, resolve) {
            let result = []
            if(row.children.length > 0) {
                result = row.children
            }else{
                if(row.isDetailed != 1) {
                    try {
                        result = await this.getChildrenInfo(row.thisLevelId) //本级id
                    } catch (error) {
                        result = []
                    }
                }
            }
            row.children = result
            if(result.length == 0) {
                row.lowestChild = true
            }
            resolve(result)
        },
        //将合同清单数据转为需要的树
        listConversionTree (arr, ParentId) {
            const tree = []
            let temp
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].ParentId == ParentId) {
                    const getObj = this.setSonData(arr[i])
                    const obj = getObj
                    temp = this.listConversionTree(arr, arr[i].ListId)
                    if (temp.length > 0) {
                        obj.children = temp
                    } else {
                        obj.isDetailed = 1 //最子级（树的最底层）为1
                        obj.children = []
                        obj.lowestChild = true
                    }
                    tree.push(obj)
                }
            }
            return tree
        },
        //将预付款、加扣款、保证金转为需要的树
        listConversionTreeOther (arr, parentId, isAdd) {
            const tree = []
            let temp
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].parentId == parentId) {
                    arr[i].uuid = getUuid()
                    const obj = arr[i]
                    temp = this.listConversionTreeOther(arr, arr[i].thisLevelId, isAdd)
                    if (temp.length > 0) {
                        obj.children = temp
                        obj.changeType = isAdd
                    } else {
                        obj.changeType = isAdd
                        obj.children = []
                        obj.lowestChild = true
                        obj.settlementAmount = obj.settlementAmount || 0
                        obj.prevTotalAmount = obj.prevTotalAmount || 0
                        obj.currentTotalSettlementAmount = obj.currentTotalSettlementAmount || 0
                        //预付款与保证金展示为比例
                        // if(obj.type == 4 || obj.type == 2) {
                        //     const contractAmount = obj.contractAmount
                        //     obj.prevTotalQuantity = contractAmount ? (obj.prevTotalAmount / contractAmount * 100).toFixed(4) * 1 : 0
                        //     const quantity = (obj.currentTotalSettlementAmount / contractAmount * 100).toFixed(4) * 1
                        //     obj.currentTotalSettlementQuantity = contractAmount ? (quantity + obj.prevTotalQuantity).toFixed(4) * 1 : 0
                        // }
                    }
                    tree.push(obj)
                }
            }
            return tree
        },
        //跳转至加扣款结算页面
        examine (row) {
            const billId = row.dtlId
            openAppClient(
                `/guochengJkkJieshuanView?isview=true&billid=${billId}`, '查看加扣款结算'
            )
        },
        //发起审核
        auditExamine () {
            this.settlementErrorList = []
            //验证保证金返质量保证金是否符合规则
            if(this.returnBond ()) {
                this.settlementErrorList = ['工程过程结算不能返还质量保证金，返还保证金不能填写非0数字，请检查！']
                this.setError('qingdan')
                this.scorllError()
                return
            }
            //验证必填项是否全是0
            if(this.isAreTheyAllZero()) {
                this.settlementErrorList = ['结算清单的本期结算金额至少有一个不能为0']
                this.setError('qingdan')
                this.scorllError()
                return
            }
            // 验证分包预付款截止本期末累计结算金额是否超合同金额
            if(this.returnAdvanceCharge()) {
                this.settlementErrorList = ['分包预付款的截止本期末累计结算金额不能超分包预付款的合同金额，请检查！']
                this.setError('qingdan')
                this.scorllError()
                return
            }
            //验证保证金本期末结算金额是否超保证金合同金额
            if(this.returnBondAmount ()) {
                this.settlementErrorList = ['扣/返还的截止本期末累计结算金额不能超保证金的合同金额，请检查！']
                this.setError('qingdan')
                this.scorllError()
                return
            }
            let sendOutList = []
            const cloneList = JSON.parse(JSON.stringify(this.acceptanceData))
            const targetList =  cloneList.filter(item=>[1, 2, 4].includes(item.type))
            if(targetList.length > 0) {
                targetList.forEach(item=>{
                    const paramList = this.flatTree(item.children)
                    sendOutList = [...sendOutList, ...paramList]
                })
                //找出所有最子级
                const detailedList = sendOutList.filter(item=>item.isDetailed == 1)
                this.setInitializationData(detailedList)
                if(this.historyDataList.length > 0) {
                    const paramsList = [httpRequest.setUnderReviewHistoryData(this.historyDataList)]
                    if(sendOutList.length > 0) {
                        //处理清单数据
                        sendOutList.forEach(item => {
                            item.billId = this.billId
                            item.settlementAmount = item.settlementAmount * 1
                            item.contractQuantity = item.contractQuantity * 1 || parseFloat(item.contractQuantity)
                            item.prevTotalQuantity = item.prevTotalQuantity * 1 || parseFloat(item.prevTotalQuantity)
                            item.settlementQuantity = item.settlementQuantity * 1 || parseFloat(item.settlementQuantity)
                            if(item.changeType != 1) {
                                item.changeType = 2
                            }
                        })
                        paramsList.push(httpRequest.updeteProjectSettlementDetailed(sendOutList))
                        //处理基本信息中用计算属性计算的参数
                        const obj = {
                            excludingDepositAmount: this.currentAmountNoBond,
                            totalBond: this.bondTotal,
                            totalAmount: this.currentAmountHaveTax,
                            includingDepositAmount: this.currentAmountNoBond + this.bondTotal,
                            settlementType: 1,
                            currentTotalAmount: ((Number(this.formData.previousTotalAmount) || 0) + (Number(this.totalSettlement.settlementAmount) || 0)).toFixed(2) * 1
                        }
                        //保存基本信息
                        paramsList.push(httpRequest.updateProjectSettlementInfo({
                            ...this.formData,
                            ...obj,
                        }))
                    }
                    Promise.all(paramsList)
                        .then(() => {
                            this.clientPop('suc', '数据保存成功')
                            location.reload()
                        })
                        .catch(() => {
                            this.clientPop('err', '数据保存失败')
                        })
                        .finally(() => {
                            hideLoading()
                        })
                }
            }
            this.setAuditParams(this.auditParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/exaDialog', '填写审核意见', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                httpRequest.conductAudit(auditParams).then(() => {
                    this.clientPop('suc', '审核成功', ()=>{
                        this.printHandel()
                    })
                })
            })
        },
        //撤回
        Withdraw () {
            httpRequest.withdraw(this.auditParams).then(() => {
                this.clientPop('suc', '撤回成功', ()=>{
                    this.printHandel()
                })
            })
        },
        //作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            //客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                httpRequest.abolishProjectSettle(auditParams).then(() => {
                    this.clientPop('suc', '作废成功', ()=>this.printHandel ())
                })
            })
        },
        //删除
        deleteData () {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作！',
                ()=>{
                    httpRequest.deleteProjectSettle({ id: this.attachId }
                    ).then(res=>{
                        if(res.code == 200) {
                            this.clientPop('suc', '删除成功', ()=>{
                                this.printHandel()
                            })
                        }
                    })
                }
            )
        },
        //操作成功后返回列表页面
        printHandel () {
            this.$router.replace('/guochengJieshuanList')
        },
        //打印
        printData () {
            const params =  {
                'reportTitle': '', //报表名
                'orgName': '', //单据机构
                'reportQRUri': '', //报表内容URI
                'billNo': '', //单据编码
                'summaryInfoItems': [ //基本信息
                ],
                'tables': [ //表格
                ]
            }
            //设置表格整体
            params.reportTitle = `工程价款结算明细表[${this.formData.period}]`
            params.orgName = this.formData.orgName
            params.reportQRUri = window.location.href
            params.billNo = this.formData.billNo
            params.summaryInfoItems = this.setPrintInfo()
            params.tables.push(this.setTableData())
            params.tables.push(this.setAuditHistoryData())
            webprintReport(params)
            // webprintReport(null)
        },
        //设置打印基本信息 tps
        setPrintInfo () {
            const target = []
            const data = this.formData
            const list = [
                ['外包方名称', data.outsourcerName, true],
                ['合同编号', data.contractId, false],
                ['合同名称', data.contractName, true],
                ['结算日期', data.settlementDate, false],
                ['本期结算金额(不含保证金)', data.excludingDepositAmount, false],
                ['保证金合计', data.totalBond, false],
                ['税率', data.taxRate, false],
                ['税额', data.taxAmount, false],
                ['本期结算金额', data.currentTotalAmount, false],
                ['本期结算内容概要', data.remarks, true],
            ]
            list.forEach(item=>{
            //设置基本信息参数
                const infoObj = {
                    'label': '标题',
                    'value': '内容',
                    'isFullRow': true //是否占整行
                }
                infoObj.label = item[0]
                infoObj.value = item[1]
                infoObj.isFullRow = item[2]
                target.push(infoObj)
            })
            return target
        },
        //设置打印的表格数据
        setTableData () {
            //设置历史期数
            const historyData = {}
            if(this.dynamicLoadingLable.length > 0) {
                this.dynamicLoadingLable.forEach(item=>{
                    historyData[item.label] = item.prop
                })
            }
            const obj = {
                'tableTitle': '结算清单',
                'tableContent': {
                    '细目编号': 'itemNo',
                    '细目名称': 'itemName',
                    '结构部位': 'structureName',
                    '计量单位': 'unit',
                    '合同数量': 'contractQuantity',
                    '合同单价': 'contractPrice',
                    '合同金额': 'contractAmount',
                    '本期结算数量': 'settlementQuantity',
                    '本期结算金额': 'settlementAmount',
                    ...historyData,
                    '截止上期末累计结算数量': 'currentTotalSettlementQuantity',
                    '截止上期末累计结算金额': 'currentTotalSettlementAmount',
                    '截止本期末累计结算数量': 'currentTotalSettlementQuantity',
                    '截止本期末累计结算金额': 'currentTotalSettlementAmount',
                },
                'tableData': this.acceptanceData, //表格数据
            }
            return obj
        },
        //添加审核历史
        setAuditHistoryData () {
            const obj = {
                'tableTitle': '审核历史',
                'tableContent': {
                    '审核级次': 'unitName',
                    '审核人': 'assignUser',
                    '审核人岗位': 'userTitle',
                    '审核时间': 'completeTime',
                    '审核意见': 'opinion',
                },
                'tableData': this.auditHistoryData, //表格数据
            }
            return obj
        },
        async exas (arg) {
            //审核
            if (arg === 'audit') {
                this.auditExamine()
            //撤回
            } else if (arg === 'undoAudit') {
                this.Withdraw()
            //作废
            } else if (arg === 'nullify') {
                this.nullify()
            //删除
            } else if (arg === 'deleteData') {
                this.deleteData()
            //打印
            } else if(arg === 'print') {
                this.printData()
            }
        },
        //设置合计
        setTotalSettlement (list, target) {
            target['settlementAmount'] = list.reduce((a, b)=>a + (Number(b.settlementAmount) || 0), 0).toFixed(2) * 1
            target['prevTotalAmount'] = list.reduce((a, b)=>a + (Number(b.prevTotalAmount) || 0), 0).toFixed(2) * 1
            target['currentTotalSettlementAmount'] = list.reduce((a, b)=>a + (Number(b.currentTotalSettlementAmount) || 0), 0).toFixed(2) * 1
            // let i = 1
            // let isWhile = true
            // while (isWhile) {
            //     if(list[0]['settleAmount' + i]) {
            //         obj['settleAmount' + i] = list.reduce((a, b)=>a + (Number(b['settleAmount' + i] ) || 0), 0).toFixed(2) * 1
            //     }else {
            //         isWhile = false
            //     }
            // }
        },
        //结算金额或数量聚焦事件
        getOldValue (row, fieldName) {
            const res = this.initializationData.some(s=>s.dtlId == row.dtlId && s.fieldName == fieldName)
            if(res) {
                return
            } else {
                const obj = {
                    dtlId: row.dtlId,
                    fieldName,
                    oldValue: row[fieldName],
                }
                this.initializationData.push(obj)
            }
        },
        //结算金额变化事件
        setAmount (row) {
            row.settlementAmount = Number(row.settlementAmount).toFixed(2) * 1
            //合同清单
            if(row.type == 1) {
                row.currentTotalSettlementAmount = ((Number(row.prevTotalAmount) || 0 ) + (Number(row.settlementAmount) || 0)).toFixed(2) * 1
            }
            //预付款
            if(row.type == 2) {
                row.currentTotalSettlementAmount = ((Number(row.prevTotalAmount) || 0 ) + (Number(row.settlementAmount) || 0)).toFixed(2) * 1
                //本期数量
                if(row.settlementAmount && row.contractAmount) {
                    row.settlementQuantity = (row.settlementAmount / row.contractAmount * 100).toFixed(4) * 1
                }
                //截止本期末数量
                if(row.currentTotalSettlementAmount && row.contractAmount) {
                    const quantity = (row.currentTotalSettlementAmount / row.contractAmount * 100).toFixed(4) * 1
                    row.currentTotalSettlementQuantity = quantity
                }
            }
            //保证金
            if(row.type == 4) {
                const contractAmount = row.contractAmount
                row.settlementAmount = row.marginType == 1 ? 0 - row.settlementAmount : row.settlementAmount
                row.currentTotalSettlementAmount = ((Number(row.prevTotalAmount) || 0 ) + (Number(row.settlementAmount) || 0)).toFixed(2) * 1
                row.settlementQuantity = contractAmount ? ((row.settlementAmount / contractAmount * 100).toFixed(4) * 1) : 0
                const quantity = (row.currentTotalSettlementAmount / contractAmount * 100).toFixed(4) * 1
                row.currentTotalSettlementQuantity = quantity
            }
        },
        //结算数量变化事件
        setQuantity (row) {
            if(row.type == 1) {
                //验证数量是否超当前施工最大数量
                if(row.settlementQuantity > row.projectLog ) {
                    row.settlementQuantity = row.projectLog
                    this.$message.error('本期结算数量不可超当前施工日志最大数量:' + row.projectLog)
                }
                row.settlementQuantity = Number(row.settlementQuantity).toFixed(4) * 1
                row.settlementAmount = parseInt((row.settlementQuantity * (row.contractPrice || 0)))
                row.currentTotalSettlementQuantity = ((Number(row.prevTotalQuantity) || 0) + (Number(row.settlementQuantity) || 0)).toFixed(4) * 1
                row.currentTotalSettlementAmount = ((Number(row.settlementAmount) || 0) + (Number(row.prevTotalAmount) || 0)).toFixed(4) * 1
            }
        },
        //验证结算类型中的必填项是否全为0(true满足,false不满足)
        isAreTheyAllZero () {
            //合同内容
            let isHeTong = true
            let isYufukuan = true
            let isBaozhengjin = true
            if(this.projectContent.children.length > 0) {
                const cloneList = JSON.parse(JSON.stringify(this.projectContent.children))
                const arrList = this.flatTree(cloneList)
                isHeTong = arrList.every(item=>{
                    if(item.isDetailed == 1) {
                        //判断是金额必填还是数量必填
                        const target = item.unit == '总额' ? item.settleAmount : item.settlementQuantity
                        return Number(target) == 0
                    } else {
                        return true
                    }
                })
            }

            //预付款
            if(this.advanceCharge.children.length > 0) {
                isYufukuan = this.advanceCharge.children.every(son=>son.settlementAmount == 0)
            }

            //保证金
            if(this.bond.children.length > 0) {
                this.bond.children && this.bond.children.forEach(item=>{
                    if(item.children && item.children.length > 0) {
                        //1扣 2返
                        isBaozhengjin = item.children.every(son=>{
                            if(son.marginType == 2) {
                                const targte = son.itemName.indexOf('-')
                                const targetStr = son.itemName.substr(targte + 1)
                                //前面已验证过返质量保证金
                                if(targetStr == '质量保证金') {
                                    return true
                                }else {
                                    return son.settlementAmount == 0
                                }
                            }else {
                                return son.settlementAmount == 0
                            }
                        })
                    }
                })
            }
            const res = [isHeTong, isYufukuan, isBaozhengjin].every(i=>i)
            return res
        },
        //验证返质量保证金(true不满足,false满足)
        returnBond () {
            let isTrue = false
            //第一层
            if(this.bond.children.length > 0) {
                this.bond.children.forEach(item=>{
                    //第二层 1扣 2返
                    item.children.length > 0 && item.children.forEach(out=>{
                        if(out.marginType == 2) {
                            const itemName = out.itemName
                            const targte = itemName.indexOf('-')
                            const targetStr = itemName.substr(targte + 1)
                            if(targetStr == '质量保证金' && Number(out.settlementAmount) !== 0) {
                                isTrue = true
                            }
                        }
                    })
                })
            }
            return isTrue
        },
        //验证分包预付款截止本期末累计金额是否超合同金额(true不满足,false满足)
        returnAdvanceCharge () {
            let isTrue = false
            if(this.advanceCharge.children.length > 0) {
                this.advanceCharge.children.forEach(item=>{
                    if(item.currentTotalSettlementAmount > item.contractAmount) {
                        isTrue = true
                    }
                })
            }
            return isTrue
        },
        //验证保证金本期末结算金额是否超合同金额(true不满足,false满足)
        returnBondAmount () {
            let isTrue = false
            if(this.bond.children.length > 0) {
                this.bond.children && this.bond.children.forEach(item=>{
                    if(item.children && item.children.length > 0) {
                        isTrue = item.children.some(son=>(son.currentTotalSettlementAmount || 0) > (son.contractAmount || 0))
                    }
                })
            }
            return isTrue
        },
        //修改历史数组
        setInitializationData (list) {
            //获取当前登录人
            const { userId, userName } = this.userInfo
            //判断是否存在修改历史记录
            if(this.historyDataList.length > 0) {
                //查找已存在历史记录的数据并根据修改的值改变changeType
                this.historyDataList.forEach(item=>{
                    list.forEach(detailed=>{
                        //当前数据是否已存在历史记录
                        if(item.dtlId == detailed.dtlId && item.changedPersonId == userId) {
                            //变更后的值与用户修改后的一致说明没有修改过
                            if(item.valueAfterChange == detailed[item.fieldName]) {
                                item.changeType = 0
                            } else {
                                item.changeType = 2
                                item.valueBeforeChange = item.valueAfterChange * 1
                                item.valueAfterChange = detailed[item.fieldName] * 1
                                item.changeTime = this.getCurrentTime()
                            }
                            //此字段用于验证修改的数据中已完成修改的数据
                            detailed.isChange = true
                        }
                    })
                })
                //遍历是否有新增的修改记录
                this.initializationData.forEach(item=>{
                    list.forEach(d=>{
                        if(item.dtlId == d.dtlId && !d.isChange) {
                            //如果修改前的值与修改后不一致则保存新增
                            if(item.oldValue != d[item.fieldName]) {
                                const obj = {
                                    billId: this.billId,
                                    billType: '1095',
                                    changeTime: this.getCurrentTime(),
                                    changeType: 1,
                                    changedPersonId: userId,
                                    changedPersonName: userName,
                                    dtlId: item.dtlId,
                                    fieldName: item.fieldName,
                                    valueAfterChange: d[item.fieldName] * 1,
                                    valueBeforeChange: item.oldValue * 1,
                                }
                                this.historyDataList.push(obj)
                            }
                        }
                    })
                })
            //不存在则新增
            }else {
                //遍历修改之前的数据对比修改之后是否一致
                this.initializationData.forEach(item=>{
                    list.forEach(d=>{
                        if(item.dtlId == d.dtlId) {
                            //如果修改前的值与修改后不一致则保存新增
                            if(item.oldValue != d[item.fieldName]) {
                                const obj = {
                                    billId: this.billId,
                                    billType: '1095',
                                    changeTime: this.getCurrentTime(),
                                    changeType: 1,
                                    changedPersonId: userId,
                                    changedPersonName: userName,
                                    dtlId: item.dtlId,
                                    fieldName: item.fieldName,
                                    valueAfterChange: d[item.fieldName] * 1,
                                    valueBeforeChange: item.oldValue * 1,
                                }
                                this.historyDataList.push(obj)
                            }
                        }
                    })
                })
            }
        },
        //将树处理为后端需要的一维数组
        flatTree (tree, list = []) {
            tree.forEach(item=>{
                const children = item.children
                delete item.children
                list.push(item)
                children && this.flatTree(children, list)
            })
            return list
        },
        //获取当前时间
        getCurrentTime () {
            const date = new Date()
            const year = date.getFullYear()
            const month = date.getMonth() + 1
            const day =  date.getDay()
            const h = date.getHours()
            const m = date.getMinutes()
            const resMonth = this.setTimeBeforeZero(month)
            const resDay = this.setTimeBeforeZero(day)
            const resH = this.setTimeBeforeZero(h)
            const resM = this.setTimeBeforeZero(m)
            return `${year}-${resMonth}-${resDay} ${resH}:${resM}`
        },
        //月、日、时、分补全前置0
        setTimeBeforeZero (data) {
            if (data < 10) {
                data = '0' + data
            }
            return data
        },
        //表格搜索结果转为树
        searchListToTree (arr, parentId) {
            const tree = []
            let temp
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].parentId == parentId) {
                    const obj = arr[i]
                    temp = this.searchListToTree(arr, arr[i].thisLevelId)
                    if (temp.length > 0) {
                        obj.children = temp
                    } else {
                        obj.isDetailed = 1 //最子级（树的最底层）为1
                        obj.children = []
                        obj.hasChildren = false
                    }
                    tree.push(obj)
                }
            }
            return tree
        },
        //表格搜索
        searchTableData () {
            if(this.cloneTbaleData.length == 0) {
                //先拷贝原数据
                this.cloneTbaleData = JSON.parse(JSON.stringify(this.acceptanceData))
            }
            if(this.searchVal) {
                //初始化数据
                const searchList = JSON.parse(JSON.stringify(this.cloneTbaleData))
                const list = this.flatTree(searchList)
                let res = []
                // 细目编号(itemNo)、细目名称(itemName)或结构部位(structureName)
                const target = ['itemNo', 'itemName', 'structureName']
                //查找细目编号
                for (let i = 0; i < target.length; i++) {
                    res = list.filter(item=>(item[target[i]] || '').indexOf(this.searchVal) > -1)
                    if(res.length > 0) break
                }
                if(res.length > 0) {
                    const tree = this.searchListToTree(res)
                    console.log(tree, ';eee')
                }
                //找到子级
                res.forEach(item=>{
                    const children = list.filter(fill=>item.thisLevelId == fill.parentId)
                    item.children = children
                })
                this.acceptanceData = res
            }else {
                this.acceptanceData = this.cloneTbaleData
            }
        },
        //设置错误标签
        setError (name) {
            console.log(name, 'name')
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.el-tab-pane {
    margin-left: -10px;
}

.form {
    margin-top: 10px;
}

.bigBox {
    padding: 0 10px;
    .top {
        margin: 0 auto;
        background: #fff;
        display: flex;
        justify-content: space-between;
        padding: 10px;
        margin-bottom: 20px;
        border-radius: 5px;
        box-shadow: 1px 1px 5px rgba(201, 198, 198, 0.804);
        .right {
            margin-left: 20px;
        }
    }
}

.goTo {
    color: blue;
    cursor: pointer;
    font-size: 12px;
}

.e-table {
    background: #fff;
}
.handle {
    margin-top: 10px;
}
.errMessage {
    color: red;
    font-size: 14px;
}

.select_box {
    display: flex;
    align-items: center;
    .label {
        margin: 0 0 0 10px;
        font-weight: bold;
        font-size: 13px;
    }
    ::v-deep .el-radio-group {
        display: flex;
        .el-radio {
            display: flex;
            align-items: center;
            margin-right: 10px;
        }
    }
}

.account_item_clear {
    ::v-deep .el-select {
        .el-select__tags {
            .el-tag {
                .el-tag__close {
                    display: none;
                }
            }
        }
    }
}
</style>
